var md5Encrypt = require("../../util/md5/md5.js");
let app = getApp();
Page({
  data: {
    appInfo: getApp(),
    imgUrl: getApp().globalData.imgUrl,
    ossImg: `${app.globalData.imgUrl}/applet_web_images/new_image`,
    baseUrl: "", // 根路径
    imgUr: "", // 图片根路径
    infoCount: {}, // 订单数量
    user_name: null, // 用户名称
    user_phone: "", // 用户手机号
    avatar_image: "/image/default_avatar.png",
    kefuisShow: false, //客服弹框
    complaintisShow: false, //申诉反馈
    mall_datas: [
      {
        img: "../../image/my-yuqi.png",
        txt: "待付款",
        status: 1,
      },
      {
        img: "../../image/my-post.png",
        txt: "待发货",
        status: 2,
      },
      {
        img: "../../image/my-shouhuo.png",
        txt: "待收货",
        status: 3,
      },
      {
        img: "../../image/my-wanjie.png",
        txt: "已完成",
        status: 4,
      },
    ],
    order_datas: [
      {
        img: "../../image/my-fahuo.png",
        txt: "待审核",
        id: 1,
        status: 1,
      },
      {
        img: "../../image/my-shouhuo.png",
        txt: "待发货",
        status: 3,
        id: 3,
      },
      {
        img: "../../image/my-zuyong.png",
        txt: "租用中",
        id: 4,
        status: 4,
      },
      {
        img: "../../image/my-yuqi.png",
        txt: "已逾期",
        id: 7,
        status: 7,
      },
      {
        img: "../../image/my-wanjie.png",
        txt: "已完成",
        status: 6,
        id: 6,
      },
    ],
    new_order_data: [
      {
        img: `${app.globalData.imgUrl}/applet_web_images/new_image/mine/my-all.png`,
        name: "全部",
        url: "./myorders/myorders",
        number: 0,
        order_status: "",
      },

      {
        img: `${app.globalData.imgUrl}/applet_web_images/new_image/mine/my-yuqi.png`,
        name: "待支付",
        url: "./myorders/myorders?id=2",
        number: 0,
        order_status: "",
      },

      {
        img: `${app.globalData.imgUrl}/applet_web_images/new_image/mine/my-shouhuo.png`,
        name: "待收货",
        url: "./myorders/myorders?id=3",
        number: 0,
        order_status: "",
      },

      {
        img: `${app.globalData.imgUrl}/applet_web_images/new_image/mine/my-zuyong.png`,
        name: "租用中",
        url: "./myorders/myorders?id=4",
        number: 0,
        order_status: "",
      },
    ],
    server_data: [
      {
        img: "../../image/my-youhui.png",
        txt: "领券中心",
        page: "/myVouchers/myVouchers",
        id: "card",
        fun: "",
        tag: "",
      },
      {
        img: "../../image/my-kefu.png",
        txt: "在线客服",
        id: "kefu",
      },
      {
        img: "../../image/my-tousu.png",
        page: "my_feedback/feedback",
        txt: "申诉反馈",
        id: "feedback",
      },
      {
        img: "../../image/my-help.png",
        page: "helpcenter/helpcenter",
        txt: "帮助中心",
        id: "helper",
      },
    ],

    recomend_list: [],
    page: {
      size: 10,
      page: 1,
      total: 0,
      pageSize: 0,
    },
    scroll: false, //是否滑动页面
    loadText: "加载中...",
    is_getOrder: false, //是否下过订单
    is_certification: false, //是否已经实名
    code_name: "",
    animation: "",
    isHide: false, //页面是否被隐藏
    is_financial: 0,
    is_warrant: 0,
    order_flag: 1,
    titleBarHeight: 0, // 导航栏文字高度
    statusBarHeight: 0, // 状态栏高度
    isCollectionCard: true, // 是否领卡
    passId: "", // 会员卡详情页
    is_add_id_card_img: 0, // 是否上传资料
    rotationChartImg: [
      {
        img: "/applet_web_images/banner/c.jpg",
      },
    ], // 轮播图图片
    authorizeHide: false // 授权弹窗
  },
  onReady() {
    this.animation = my.createAnimation({
      duration: 500,
    });
    // 获取会员卡状态
    this.getOpenCardState();
  },


  // 跳转省钱页面
  jumpTabbar({ target: { dataset: { url } }}) {
    my.switchTab({
      url,
      fail: () => {
        my.navigateTo({
          url,
        });
      },
    });
  },

  server_jump({
    target: {
      dataset: { url },
    },
  }) {
    my.navigateTo({
      url,
    });
  },

  // 退出登陆
  exitLogin() {
    const userInfo = my.getStorageSync({key: 'username_and_avatar'})

    if(userInfo.success) {
      my.confirm({
        title: '提示',
        content: '确定退出登录？',
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        success: (result) => {
          const { confirm } = result
          if(confirm) {
            my.removeStorage({key: 'userInfo'})
            my.removeStorage({key: 'username_and_avatar'})
            this.setData({
              user_name: null,
              user_phone: '',
              avatar_image: "/image/default_avatar.png"
            })
          }
        },
      });
    }

  },

  // 加群
  addGroup() {
    my.ap.openURL({
      url: "alipays://platformapi/startapp?appId=68687451&url=%2Fwww%2Fbc-join.html%3Foid%3D2023020316330500021149%26businessId%3D2023020316330500021149%26businessType%3D18%26source%3DOTHERS",
    });
  },

  onRenderSuccess(e) {
    console.log("success", e);
  },
  onRenderFail(e) {
    console.log("err", e);
  },
  onReachBottom() {
    var obj = this;
    //console.log("触底加载");
    if (this.data.page.page < this.data.page.pageSize) {
      this.setData({
        scroll: true,
        page: {
          page: this.data.page.page + 1,
          size: this.data.page.size,
          total: this.data.page.total,
        },
      });

      // this.getRecommendGoods();
    } else {
      this.setData({
        scroll: true,
        loadText: "没有更多了哦",
      });

      setTimeout(function () {
        obj.setData({
          loadText: "",
          scroll: false,
        });
      }, 2000);
    }
  },
  // 获取为你推荐
  // getRecommendGoods() {
  //   let app = getApp();
  //   let vm = this;
  //   // 优惠券
  //   my.request({
  //     url: app.globalData.testUrl + "/Api/goods/recommendGoods",
  //     data: {
  //       page_size: vm.data.page.size,
  //       page: vm.data.page.page,
  //     },
  //     method: "post",
  //     dataType: "json",
  //     success: (res) => {
  //       //console.log("热门推荐", res.data);
  //       if (res.data.status == "1001") {
  //         let list = [...this.data.recomend_list, ...res.data.data.data];
  //         vm.setData({
  //           recomend_list: list,

  //           "page.total": res.data.data.total,
  //           "page.pageSize": Math.ceil(res.data.data.total / vm.data.page.size),
  //         });
  //         // console.log(list)
  //       }
  //     },

  //     complete: function (res) {
  //       my.hideLoading(); //加载结束
  //     },
  //   });
  // },
  translate(_bol) {
    let position = 0;
    if (_bol) {
      position = position + 10;
    } else {
      position = position - 10;
    }
    if (typeof this.animation != "undefined") {
      this.animation.translate(0, position).step();
      this.setData({ animation: this.animation.export() });
    }
  },
  reset() {
    if (typeof this.animation != "undefined") {
      this.animation.translate(0, 0).step();
      this.setData({ animation: this.animation.export() });
    }
  },

  // 订单切换
  switchOrder(e) {
    const {
      target: { dataset },
    } = e;
    this.setData({
      order_flag: dataset.flag,
    });
  },

  //获取优惠券
  getMyVouchers(action) {
    var obj = this;

    //获取用户信息
    my.getStorage({
      key: "userInfo",
      success: function (result) {
        // console.log(result.data);
        if (typeof result.data != "undefined" && result.data != null) {
          var phone = result.data.phone;

          var voucherParam = {
            version: app.globalData.version,
            device: app.globalData.device,
            signType: app.globalData.signType,
            phone: phone,
          };
          var voucherStr = md5Encrypt.md5(voucherParam);

          // 优惠券
          my.request({
            url: app.globalData.testUrl + "Api/coupon/couponsList",
            method: "POST",
            data: {
              version: app.globalData.version,
              device: app.globalData.device,
              signType: app.globalData.signType,
              phone: phone,
              token: voucherStr,
            },
            dataType: "json",
            success: function (res) {
              if (res.data.status == "1001") {
                var voucherLen = 0;
                for (var i = 0; i < res.data.data.length; i++) {
                  if (res.data.data[i].my_cou_status == "1") {
                    voucherLen += 1;
                  }
                }

                if (voucherLen == 0) {
                  obj.setData({
                    noVoucher: true,
                  });
                }

                for (var j = 0; j < obj.data.listData.length; j++) {
                  if (
                    obj.data.listData[j].event == "myVouchers" &&
                    voucherLen > 0
                  ) {
                    obj.data.listData[j].isShow = true;
                  } else if (
                    obj.data.listData[j].event == "myVouchers" &&
                    voucherLen == 0
                  ) {
                    obj.data.listData[j].isShow = false;
                  }
                }

                obj.setData({
                  listData: obj.data.listData,
                });
              } else {
                obj.setData({
                  noVoucher: true,
                });
              }
            },
            complete: function (res) {
              if (action == "load") {
                my.hideLoading(); //加载结束
              } else if (action == "pulldown") {
                setTimeout(function () {
                  my.stopPullDownRefresh(); //停止刷新
                }, 1000);
              }
            },
          });
        } else {
          for (var k = 0; k < obj.data.listData.length; k++) {
            if (obj.data.listData[k].event == "myVouchers") {
              obj.data.listData[k].isShow = false;
            }
          }
          if (action == "load") {
            my.hideLoading(); //加载结束
          } else if (action == "pulldown") {
            setTimeout(function () {
              my.stopPullDownRefresh(); //停止刷新
            }, 1000);
          }
        }
      },
    });
  },

  // 获取用户状态
  getUserInfoState() {
    let app = getApp();
    my.request({
      url: app.globalData.testUrl + "/api/user/getUserInfo",
      method: "post",
      data: {
        zm_user_id: app.globalData.user_id,
      },
      dataType: "json",
      success: ({ data: { data } }) => {
        const { user_order_status_info, is_add_id_card_img } = data;

        this.data.new_order_data.forEach((item, index) => {
          const { name, order_status, number } = user_order_status_info[index];
          if (item.name === name) {
            item.number = number;
            item.order_status = order_status;
          }
        });
        this.setData({
          new_order_data: this.data.new_order_data,
          is_add_id_card_img,
        });
      },
    });
  },

  // 获取用户信息
  getOpenUserInfo() {
    my.getOpenUserInfo({
      success: (res) => {
          let {
            code,
            avatar,
            nickName: user_name
          } = JSON.parse(res.response).response
          if(code === '10000') {
            this.setData({
              user_name,
              avatar_image: avatar
            })
            my.setStorage({
              key: 'username_and_avatar',
              data: {
                avatar,
                username: user_name,
              },
            });
          }
      },
      fail: (err) => {
          console.log(err)
      }
  });
  },

  // 关闭授权弹窗
  onHideAuthorize() {
    this.setData({
      authorizeHide: false
    })
  },  

  onSetPhoneState({ phone }) {
    this.setData({
      user_phone: phone
    })
  },

  onLoad(option) {
    my.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#ffffff'
    })

    const { titleBarHeight, statusBarHeight } = my.getSystemInfoSync();
    this.setData({
      titleBarHeight,
      statusBarHeight,
    });

    const { platform } = option
    let app = getApp();
    app.globalData.exclusivePrice = "";

    app.setShareChannel(platform)
  },
  onGetAuthorize(res) {
    //获取基础信息
    let that = this;
    my.getOpenUserInfo({
      fail: () => {},
      success: (res) => {
        let userInfo = JSON.parse(res.response).response; // 以下方的报文格式解析两层 response
        my.setStorageSync({
          key: "base_userInfo",
          data: userInfo,
        });
        that.setData({
          avatar_image: userInfo.avatar,
        });
      },
    });
  },
  // mine_getAuthCode() {
  //   var app = getApp();
  //   app.getAuthCode((res) => {
  //     if (!res) {
  //       return;
  //     }
  //     const {
  //       data: { avatar, phone: user_phone },
  //     } = my.getStorageSync({ key: "userInfo" });
  //     this.setData({
  //       avatar_image: avatar || "../../image/my-avatar.png",
  //       user_phone,
  //     });
  //     this.getUserInfoState();
  //   });
  // },
  // 查看权益
  queryEquity() {
    const { data } = my.getStorageSync({key: 'userInfo'})
    if(!data) {
      this.setData({
        authorizeHide: true
      })
      return
    }

    let passId = this.data.passId.match(/[?&]p=([^&]+)/);
    
    my.openCardDetail({
      passId: passId[1], // 实际开发中请使用有效的 passId 值。
      success: (res) => {
        console.log(res);
      },
      fail: (err) => {
        const { error } = err;
        if (error === 1) {
          my.showToast({
            type: "none",
            content: "网络异常，请重试！",
          });
        }
      },
    });
  },
  // 获取开启会员卡状态
  getOpenCardState() {
    const { testUrl, user_id } = getApp().globalData;
    my.request({
      url: `${testUrl}/api/activity/openVipCardStatus`,
      method: "POST",
      data: {
        zm_user_id: user_id,
        template_id: "20230228000000004431380000300814",
      },
      success: (res) => {
        const {
          data: { code, data: passId },
        } = res;
        if (code !== 1) {
          this.setData({
            isCollectionCard: true,
          });
          return;
        }
        // 开卡成功，显示权益
        this.setData({
          isCollectionCard: false,
          passId,
        });
      },
    });
  },
  // 开启会员卡
  onOpenCard() {
    const { data } = my.getStorageSync({key: 'userInfo'})
    if(!data) {
      this.setData({
        authorizeHide: true
      })
      return
    }

    var plugin = requirePlugin("alipassToolKit"); // 引用名称需与 app.json 中定义名称相同
    let params = {
      cardParams: {
        //开卡入参，
        templateId: "20230228000000004431380000300814", // 开卡的卡模板ID
        templateAppId: "2021002129611863", // 卡模板ID 所关联的 AppId
        pageType: "half", //默认是 half
      },
      callback: (res) => {
        const { resultCode } = res;
        if (res.success === true) {
          if (resultCode === "10000") {
            // 动态展示查看权益或开卡成功
            this.getOpenCardState();
          }
          console.log("----- success");
        }
      },
    };
    plugin.openCard(params); // 接口参数说明如下
  },

  // getcertification() {
  //   //获取实名结果
  //   let vm = this;
  //   let app = getApp();

  //   //是否下过订单
  //   my.request({
  //     url: app.globalData.testUrl + "/Api/order/is_getOrder",
  //     method: "get",
  //     data: {
  //       zm_user_id: app.globalData.user_id,
  //     },
  //     success: (res) => {
  //       if (res.data.status == "1001") {
  //         vm.setData({
  //           is_financial: res.data.data.is_financial,
  //           is_warrant: res.data.data.is_warrant,
  //           code_name: res.data.data.user_name,
  //         });
  //         //是否已经实名
  //         my.request({
  //           url: app.globalData.testUrl + "/Api/order/is_certification",
  //           method: "get",
  //           data: {
  //             zm_user_id: app.globalData.user_id,
  //           },
  //           success: (res) => {
  //             //console.log("是否实名认证",res);
  //             if (res.data.status == "1001") {
  //               vm.setData({
  //                 is_getOrder: true,
  //                 is_certification: true,
  //               });
  //             } else {
  //               let _bol = true;
  //               let _second = 0;
  //               let sss = setInterval(() => {
  //                 if (_second == 3) {
  //                   clearInterval(sss);
  //                   vm.reset();
  //                   return;
  //                 }
  //                 vm.translate(_bol);
  //                 _bol = !_bol;
  //                 _second += 0.5;
  //               }, 500);

  //               vm.setData({
  //                 is_getOrder: true,
  //                 is_certification: false,
  //               });
  //             }
  //           },
  //         });
  //       } else {
  //         vm.setData({
  //           is_getOrder: true,
  //         });
  //       }
  //     },
  //   });
  // },
  onHide() {
    // 页面隐藏
    this.setData({
      isHide: true,
    });
  },


  onShow() {
    let app = getApp();

    // 设置返回按钮样式
    my.setBackButton({
      color: "#C3D4F6",
    });
    const { user_id } = app.globalData
    if(user_id) {
      this.getUserInfoState();
    }

    my.getStorage({
      key: 'userInfo',
      success: (res) => {
        
        const { data } = res
        if (data) {
          const { phone } = data
          if(!phone) {
            this.setData({
              authorizeHide: true
            })
          } else {
            this.setData({
              user_phone: phone
            })
          }
        } else { // 如果没有用户信息直接唤起弹窗
          this.setData({
            authorizeHide: true
          })
        }
      },
      fail: (err) => {
        console.log(err)
      }
    });

    my.getStorage({
      key: 'username_and_avatar',
      success: (res) => {
        const { data } = res
        if(data) {
          const {     
            avatar,
            username: user_name, } = data
            this.setData({
              avatar_image: avatar,
              user_name
            })
        }
      }
    })

    this.setData({
      // baseUrl: app.globalData.testUrl,
      testUrl: app.globalData.testUrl,
      imgUr: app.globalData.imgUrl,
      recomend_list: [],
      page: {
        pageSize: 0,
        size: 10,
        page: 1,
        total: 0,
      },
    });
    // this.getRecommendGoods();
  },

  // getmyInfo() {
  //   let vm = this;
  //   let app = getApp();
  //   // 获取优惠券与待发货数量
  //   my.request({
  //     url: app.globalData.testUrl + '/Api/my/myInfo',
  //     method: 'POST',
  //     data: {
  //       user_phone: vm.data.user_phone,
  //       user_id: user_id ? user_id : ''
  //     },
  //     success: (res) => {
  //       //console.log('列表', res);
  //       if (res.data.status == '1001') {
  //         let _order_data = []; // 租机订单
  //         let _mall_data = []; // 商城订单
  //         for (let item of vm.data.order_datas) {
  //           for (let item1 of res.data.data.order_count) {
  //             if (item1.order_status == item.status) {
  //               item.tag = item1.number;
  //             }
  //             if (item1.order_status == 0) {
  //               item.tag = false;
  //             }
  //           }
  //           _order_data.push(item);
  //         }
  //         for (let item of vm.data.mall_datas) {
  //           for (let item1 of res.data.data.hidden_goods) {
  //             if (item1.status == item.status) {
  //               item.tag = item1.num;
  //             }
  //             if (item1.status == 0) {
  //               item.tag = false;
  //             }
  //           }
  //           _mall_data.push(item);
  //         }
  //         let _server_data = this.data.server_data;
  //         _server_data[0].tag = res.data.data.cou_coupon_count;
  //         vm.setData({
  //           order_datas: _order_data,
  //           server_data: _server_data,
  //           mall_datas: _mall_data
  //         })
  //       }
  //     }
  //   });
  // },
  jumpPage(e) {
    const { data } = my.getStorageSync({key: 'userInfo'})
    if(!data) {
      this.setData({
        authorizeHide: true
      })
      return
    }
    const { url } = e.target.dataset;
    my.navigateTo({
      url,
    });
  },

  // 跳转到订单列表
  toOrderList(e) {
    let id = e.target.dataset.id;

    my.navigateTo({
      url: "./myorders/myorders?id=" + id,
    });
  },
  toHiddenOrderList(e) {
    let id = e.target.dataset.status;

    // console.log('点击', id, status);
    my.navigateTo({
      url: "../buynow/myorder/myorder?id=" + id,
    });
  },
  toAllList() {
    const { data } = my.getStorageSync({key: 'userInfo'})
    if(!data) {
      this.setData({
        authorizeHide: true
      })
      return
    }

    //全部订单
    if (this.data.order_flag == 1) {
      //租机订单
      my.navigateTo({
        url: "./myorders/myorders",
      });
    }
  },
  toServer(e) {
    // console.log('id', e.target.dataset.id);
    let id = e.target.dataset.id;
    if (id == "kefu") {
      return;
      // });
    } else if (id == "feedback") {
      this.showcomplaint();
    } else if (id == "card") {
      my.navigateTo({
        url: "/page/rent/coupon/coupon",
      });
    } else {
      let url = e.target.dataset.url;
      my.navigateTo({
        url: url,
      });
    }
  },
  onPullDownRefresh(e) {
    //下拉刷新监听事件
    my.stopPullDownRefresh();
    // 获取会员卡状态
    this.getOpenCardState();
  },
  uploadCodeImg(e) {
    const { data } = my.getStorageSync({key: 'userInfo'})
    if(!data) {
      this.setData({
        authorizeHide: true
      })
      return
    }

    //转跳实名认证页面
    let vm = this;
    
    if (vm.data.is_certification) {
      //已实名
      my.navigateTo({
        url:
          "upload_codeImg/upload_codeImg?codeName=" +
          vm.data.code_name +
          "&is_financial=" +
          vm.data.is_financial +
          "&is_warrant=" +
          vm.data.is_warrant +
          "&t=1",
      });
    } else {
      //未实名
      my.navigateTo({
        url:
          "upload_codeImg/upload_codeImg?codeName=" +
          vm.data.code_name +
          "&is_financial=" +
          vm.data.is_financial +
          "&is_warrant=" +
          vm.data.is_warrant +
          "&t=0",
      });
    }
  },
  pingTaiPhone() {
    //平台客服
    let app = getApp();
    my.makePhoneCall({
      number: app.globalData.service_phone,
    });
  },
  pre_sale_phone() {
    //售前客服
    let app = getApp();
    my.makePhoneCall({
      number: app.globalData.pre_sale_phone,
    });
  },
  closekefu() {
    this.setData({
      kefuisShow: false,
    });
  },
  showkefu() {
    this.setData({
      kefuisShow: true,
    });
  },
  closecomplaint() {
    this.setData({
      complaintisShow: false,
    });
  },
  showcomplaint() {
    this.setData({
      complaintisShow: true,
    });
  },
  tocomplaint() {
    this.setData({
      complaintisShow: false,
    });
    my.navigateTo({
      url: "my_feedback/feedback",
    });
  },
});
